﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MINERP.BLL.Statistics;
using MINERP.MODEL.FoundationModel;
using FastReport;
using MINERP.Statistics.Forms;
using MINERP.COM;
using DevExpress.XtraGrid;
using DevExpress.XtraPrinting;
using MINERP.ComControls.Extension;

namespace MINERP.Statistics.ShopBill
{
    public partial class FrmShopBillIndex2 : Form
    {
        public FrmShopBillIndex2()
        {
            InitializeComponent();
        }

        private static FrmShopBillIndex2 _instance;

        public static FrmShopBillIndex2 GetInstance
        {
            get
            {
                if (_instance == null || _instance.Disposing)
                {
                    _instance = new FrmShopBillIndex2();
                }

                return _instance;
            }
        }
        BillIndexBLL2 _bll = new BillIndexBLL2();
        private void FrmShopBillIndex2_Load(object sender, EventArgs e)
        {
            dateTimePickerStartDate.Text = DateTime.Now.ToShortDateString();
            dateTimePickerEndDate.Text = DateTime.Now.ToShortDateString();
            splitContainerBottom2.Panel1Collapsed = false;
            splitContainerBottom2.Panel2Collapsed = true;

        }

        private void textEditHelpCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (Keys.Enter == e.KeyCode)
            {
                cbShop.DisplayMember = "ShopName";
                cbShop.ValueMember = "ShopId";
                cbShop.DataSource = _bll.GetShopInfoByHelpCode(textEditHelpCode.Text.Trim());


            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {

            string productCode = textEditProductBarcode.Text.Trim();
            string shopBillId = textEditShopBillId.Text.Trim();
            if ((string.IsNullOrEmpty(productCode) || productCode.Equals("0")) && string.IsNullOrEmpty(shopBillId) || shopBillId.Equals("0"))
            {
                //DateTime dateStart = dateTimePickerStartDate.Value.Date;
                //DateTime dateEnd = dateTimePickerEndDate.Value.Date;
                DateTime start = dateTimePickerStartDate.Value.Date;
                DateTime end = dateTimePickerEndDate.Value.AddDays(1).Date.AddSeconds(-1);
                Shop_Info info = (Shop_Info)cbShop.SelectedItem;
                if (info != null)
                {
                    textEditShopName.Text = info.ShopName;
                    gridControlBillIndex.DataSource = _bll.GetShopBillInfo(start, end, info.ShopId, cbPay.SelectedIndex);
                    gridControlBillIndex.RefreshDataSource();
                }
            }
            else if (string.IsNullOrEmpty(shopBillId) || shopBillId.Equals("0"))
            {

                if (productCode.Length == 10)
                {

                }
                else
                {
                    productCode = "2" + productCode.PadLeft(9, '0');
                }
                string shopName = "";
                gridControlBillIndex.DataSource = _bll.GetListByBarCode(productCode, out shopName);
                textEditShopName.Text = shopName;
                gridControlBillIndex.RefreshDataSource();
            }
            else if ((string.IsNullOrEmpty(productCode) || productCode.Equals("0")))
            {
                int shopbillId = Convert.ToInt32(shopBillId);
                string shopName = "";
                gridControlBillIndex.DataSource = _bll.GetListByBillID(shopbillId, out shopName);
                textEditShopName.Text = shopName;
                gridControlBillIndex.RefreshDataSource();
            }




        }

        private void simpleButtonIndexPrint_Click(object sender, EventArgs e)
        {

        }

        private void simpleButtonDisplayDetail_Click(object sender, EventArgs e)
        {
            S_Bill_Info sbi = (S_Bill_Info)gridViewBillIndex.GetFocusedRow();
            if (sbi != null)
            {
                splitContainerBottom2.Panel1Collapsed = true;
                splitContainerBottom2.Panel2Collapsed = false;
                //CurrBillID = Convert.ToInt32(e.CellValue);
                PrintBill(_bll.GetBillToView(sbi.BillId));
            }
        }

        private void gridViewBillIndex_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0 && e.Column.Name == "gridColumnBillStatus")
            {
                if (Convert.ToInt32(e.CellValue) == (int)ShopBillStatus.UnCheckOut)
                {
                    e.DisplayText = "未结账";
                    e.Appearance.BackColor = Color.LightPink;
                }
                else
                {
                    e.DisplayText = "已结账";
                    e.Appearance.BackColor = Color.LightGreen;
                }

            }
        }
        int CurrBillID = 0;
        private void gridViewBillIndex_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.RowHandle >= 0 && e.Column.Name == "gridColumnBillid")
            {
                splitContainerBottom2.Panel1Collapsed = true;
                splitContainerBottom2.Panel2Collapsed = false;
                CurrBillID = Convert.ToInt32(e.CellValue);
                PrintBill(_bll.GetBillToView(CurrBillID));

            }
        }
        public void PrintBill(SHOP_Bill_Info sbinfo)
        {
            #region 组织打印数据
            double Para_TotalNum = 0;//照片总张数
            double Para_TotalAreas = 0;//照片总面积
            double Para_TotalCount = 0;//本期金额
            double Para_Sum = 0;//产品总数
            double Para_TotalPrintCount = 0;//输出金额
            double Para_TotalProductCount = 0;//产品金额

            bool IsNeedPrintMoney = true;
            DataTable tableTitle = CreateShopBillTitle();
            DataRow titleRow = tableTitle.NewRow();
            titleRow["ShopName"] = sbinfo.Shop.ShopName;
            titleRow["Tel1"] = sbinfo.Shop.Tel1;
            titleRow["Tel2"] = sbinfo.Shop.Tel2;
            titleRow["ShopId"] = sbinfo.Shop.ShopId;
            titleRow["shopKeeper"] = sbinfo.Shop.ShopKeeper;
            titleRow["QQ"] = sbinfo.Shop.QQ;
            titleRow["BillId"] = sbinfo.BillId;
            titleRow["BillOrderCode"] = sbinfo.BillOrderCode;
            titleRow["CreateTime"] = sbinfo.CreateTime;
            titleRow["Adress"] = sbinfo.Shop.Address;
            titleRow["CheckOutType"] = sbinfo.CheckType;
            titleRow["Remark"] = sbinfo.Shop.Remark;
            //if (IsNeedPrintMoney)
            //{
            //    titleRow["Balance"] = sbinfo.ShopBalance;
            //    titleRow["BillCount"] = sbinfo.BillCount;
            //}
            //else
            //{
            //    titleRow["Balance"] = 0;
            //    titleRow["BillCount"] = 0;
            //}
            if (IsNeedPrintMoney)
            {
                titleRow["Balance"] = sbinfo.ShopBalance;
                titleRow["BillCount"] = sbinfo.BillCount;
            }
            else
            {
                titleRow["Balance"] = 0;
                titleRow["BillCount"] = 0;
            }
            titleRow["Salesman"] = sbinfo.Salesman;
            titleRow["CreditLevel"] = sbinfo.CreditLevel == null ? 0 : sbinfo.CreditLevel;
            tableTitle.Rows.Add(titleRow);

            tableTitle.TableName = "tableTitle";


            DataTable tableDetail = CreateShopBillDetail();
            DataTable tableSubDetail = CreateShopBillSubDetail();
            List<Bill_Detail_Info> detailList = sbinfo.List_Detail.ToList();

            foreach (Bill_Detail_Info billDetail in detailList)
            {
                DataRow row = tableDetail.NewRow();
                row["BillDetailId"] = billDetail.BillDetailId;
                row["OrderInfoCode"] = billDetail.OrderInfoCode;
                row["OrderProductName"] = billDetail.OrderProductName;
                row["CtmName"] = billDetail.CtmName;
                row["Remark"] = billDetail.Remark;
                row["OrderBagName"] = billDetail.OrderBagName;

                tableDetail.Rows.Add(row);
                List<Bill_Detail_Detail_Info> subDetail = billDetail.ListDetail_Detail.ToList();
                foreach (Bill_Detail_Detail_Info detail in subDetail)
                {
                    DataRow rowSub = tableSubDetail.NewRow();
                    rowSub["DetailName"] = detail.DetailName;
                    rowSub["BillDetailId"] = billDetail.BillDetailId;
                    rowSub["Spec"] = detail.Spec;
                    rowSub["Num"] = detail.Num;
                    rowSub["UnitPrice"] = detail.UnitPrice;
                    rowSub["DetailRemark"] = detail.DetailRemark;
                    if (IsNeedPrintMoney)
                    {
                        rowSub["Count"] = detail.Count;
                    }
                    else
                    {
                        rowSub["Count"] = 0;
                    }

                    rowSub["Area"] = detail.Area;
                    rowSub["Type"] = detail.Type;
                    tableSubDetail.Rows.Add(rowSub);

                    if (detail.Type == 1)//是输出类型
                    {
                        Para_TotalNum += detail.Num;
                        Para_TotalAreas += detail.Area;
                        Para_TotalPrintCount += detail.Count;
                    }
                    else if (detail.Type == 0)
                    {
                        Para_TotalProductCount += detail.Count;
                    }
                    Para_TotalCount += detail.Count;
                }
                Para_Sum++;

            }

            tableDetail.TableName = "tableDetail";
            tableSubDetail.TableName = "tableSubDetail";
            DataTable tableBottom = CreateFahuoTable();
            #endregion



            #region 打印报表
            DataSet set = new DataSet("ds");
            set.Tables.Add(tableTitle);
            set.Tables.Add(tableDetail);
            set.Tables.Add(tableSubDetail);
            set.Tables.Add(tableBottom);

            set.WriteXml(@"C:\Windows\xmldata\PrintShopBill.xml", XmlWriteMode.WriteSchema);
            Report report = new Report();
            report.Load(Application.StartupPath + "\\Report\\PrintShopBill.frx");
            report.RegisterData(tableTitle, "tableTitle");
            report.RegisterData(tableDetail, "tableDetail");
            report.RegisterData(tableSubDetail, "tableSubDetail");
            //设置合计参数
            report.SetParameterValue("Para_TotalNum", Para_TotalNum);
            report.SetParameterValue("Para_TotalAreas", Para_TotalAreas);
            report.SetParameterValue("Para_TotalCount", Para_TotalCount);
            report.SetParameterValue("Para_Sum", Para_Sum);
            report.SetParameterValue("Para_TotalPrintCount", Para_TotalPrintCount);
            report.SetParameterValue("Para_TotalProductCount", Para_TotalProductCount);
            //report.RegisterData(tableBottom, "tableBottom");
            report.Preview = previewControl1;
            previewControl1.Refresh();
            previewControl1.Show();
            report.Show();
            #endregion


        }
        /// <summary>
        /// 创建title表
        /// </summary>
        /// <returns></returns>
        private DataTable CreateShopBillTitle()
        {
            DataTable table = new DataTable();
            table.Columns.Add("ShopName", typeof(string));
            table.Columns.Add("Tel1", typeof(string));
            table.Columns.Add("Tel2", typeof(string));
            table.Columns.Add("ShopId", typeof(int));
            table.Columns.Add("BillOrderCode", typeof(string));
            table.Columns.Add("shopKeeper", typeof(string));
            table.Columns.Add("QQ", typeof(string));
            table.Columns.Add("BillId", typeof(string));
            table.Columns.Add("CreateTime", typeof(DateTime));
            table.Columns.Add("Balance", typeof(double));
            table.Columns.Add("BillCount", typeof(double));
            table.Columns.Add("CreditLevel", typeof(int));
            table.Columns.Add("Salesman", typeof(string));
            table.Columns.Add("Adress", typeof(string));
            table.Columns.Add("CheckOutType", typeof(string));
            table.Columns.Add("Remark", typeof(string));
            return table;

        }
        /// <summary>
        /// 创建明细产品
        /// </summary>
        /// <returns></returns>
        private DataTable CreateShopBillDetail()
        {
            DataTable table = new DataTable();
            table.Columns.Add("BillDetailId", typeof(int));
            table.Columns.Add("OrderInfoCode", typeof(string));
            table.Columns.Add("OrderProductName", typeof(string));
            table.Columns.Add("CtmName", typeof(string));
            table.Columns.Add("Remark", typeof(string));
            table.Columns.Add("OrderBagName", typeof(string));
            return table;
        }
        /// <summary>
        /// 创建明细收费项目表
        /// 
        /// </summary>
        /// <returns></returns>
        private DataTable CreateShopBillSubDetail()
        {
            DataTable table = new DataTable();
            table.Columns.Add("BillDetailId", typeof(int));
            table.Columns.Add("DetailName", typeof(string));
            table.Columns.Add("Spec", typeof(string));
            table.Columns.Add("Num", typeof(int));
            table.Columns.Add("UnitPrice", typeof(double));
            table.Columns.Add("Count", typeof(double));
            table.Columns.Add("Area", typeof(double));
            table.Columns.Add("Type", typeof(int));
            table.Columns.Add("DetailRemark", typeof(string));
            return table;
        }
        /// <summary>
        /// 创建发货信息表
        /// </summary>
        /// <returns></returns>
        private DataTable CreateFahuoTable()
        {
            DataTable table = new DataTable("tableBottom");
            table.Columns.Add("ConsigneeName", typeof(string));
            table.Columns.Add("ConsigneeTelePhone", typeof(string));
            table.Columns.Add("DistributionAddress", typeof(string));
            table.Columns.Add("BusTimetable", typeof(string));//收货单位
            table.Columns.Add("ReMark", typeof(string));
            table.Columns.Add("DistributionMode", typeof(string));
            table.Columns.Add("Fahuodanwei", typeof(string));
            table.Columns.Add("Fahuodianhua", typeof(string));

            return table;
        }

        private void simpleButtonReturn_Click(object sender, EventArgs e)
        {
            splitContainerBottom2.Panel1Collapsed = false;
            splitContainerBottom2.Panel2Collapsed = true;
            simpleButtonExportEx.Visible = false;
        }

        private void simpleButtonExport_Click(object sender, EventArgs e)
        {
            Shop_Info info = (Shop_Info)cbShop.SelectedItem;
            if (info != null)
            {
               // DevGridViewExport.ExportToExcel(textEditShopName.Text, gridViewBillIndex);
                DevControlExtension.ExportToExcel(gridControlBillIndex, this, info.ShopName+"索引");
            }
            //SaveFileDialog saveFileDialog = new SaveFileDialog();
            //saveFileDialog.Filter = "文本文件 (*.txt)|*.txt|pdf(*.pdf)|*.pdf|电子表格(*.xls)|*.xls|html(*.html)|*.html";
            ////saveFileDialog.AddExtension = true;
            //saveFileDialog.FilterIndex = 3;
            //saveFileDialog.RestoreDirectory = true;
            //saveFileDialog.Title = "导出Excel文件到";
            //saveFileDialog.FileName = textEditShopName.Text;
            //if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            //{
            //    string fileName = saveFileDialog.FileName;
            //    if (saveFileDialog.OpenFile() != null)
            //    {
            //        switch (saveFileDialog.FilterIndex)
            //        {
            //            case 3:
            //                XlsExportOptions xmlExport = new XlsExportOptions(true, true);
            //                gridViewBillIndex.ExportToXls(fileName, true);
            //                return;
            //            case 4:
            //                gridViewBillIndex.ExportToHtml(fileName);
            //                return;
            //            case 2:
            //                gridViewBillIndex.ExportToPdf(fileName);
            //                return;
            //            case 1:
            //                this.gridViewBillIndex.ExportToText(fileName);
            //                return;
            //            default:
            //                break;
            //        }
            //    }

            //}
        }

        private void simpleButtonUpdate_Click(object sender, EventArgs e)
        {
            FrmBillEdit frm = new FrmBillEdit(CurrBillID);
            frm.MdiParent = this.ParentForm;
            frm.WindowState = FormWindowState.Maximized;
            frm.Show();
        }

        private void FrmShopBillIndex2_FormClosing(object sender, FormClosingEventArgs e)
        {
            _instance = null;
        }
        DataSet setEx = new DataSet();
        private void simpleButtonPrint_Click(object sender, EventArgs e)
        {

            DateTime dateStart = dateTimePickerStartDate.Value.Date;
            DateTime dateEnd = dateTimePickerEndDate.Value.AddDays(1).Date.AddSeconds(-1); ;
            Shop_Info info = (Shop_Info)cbShop.SelectedItem;
            if (info != null)
            {
                splitContainerBottom2.Panel1Collapsed = true;
                splitContainerBottom2.Panel2Collapsed = false;
                simpleButtonExportEx.Visible = true;
                Report report = new Report();
                if (chkIsShowdetail.Checked)
                {
                    DataSet set = _bll.GetAllBillByDateAndid(dateStart, dateEnd, info.ShopId);
                    setEx = set;

                    set.WriteXml(@"C:\Windows\xmldata\PrintShopAllBill.xml", XmlWriteMode.WriteSchema);

                    if (radioButtonBill.Checked)
                    {
                        report.Load(Application.StartupPath + "\\Report\\PrintShopAllBill.frx");
                    }
                    else
                    {
                        report.Load(Application.StartupPath + "\\Report\\PrintShopAllProduct.frx");
                    }
                }
                else
                {
                    DataSet set = _bll.GetAllBillIndexByDateAndid(dateStart, dateEnd, info.ShopId);
                    setEx = set;

                    set.WriteXml(@"C:\Windows\xmldata\PrintShopAllBillNoDetail.xml", XmlWriteMode.WriteSchema);

                    if (radioButtonBill.Checked)
                    {
                        report.Load(Application.StartupPath + "\\Report\\PrintShopAllBillNoDetail.frx");
                    }
                    else
                    {
                        report.Load(Application.StartupPath + "\\Report\\PrintShopAllProductNoDetail.frx");
                    }

                }

                report.SetParameterValue("startTime", dateStart);
                report.SetParameterValue("endTime", dateEnd);
                report.SetParameterValue("shopName", info.ShopName);
                //report.RegisterData(tableBottom, "tableBottom");
                report.Preview = previewControl1;
                previewControl1.Refresh();
                previewControl1.Show();
                report.Show();
            }
            else
            {
                MessageBox.Show("请先选择商户和时间", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void simpleButtonExportEx_Click(object sender, EventArgs e)
        {
            if (setEx.Tables.Count == 0)
            {
                MessageBox.Show("请先返回选择", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            else
            {
                if (chkIsShowdetail.Checked)
                {
                    gridControlForExport.DataSource = setEx.Tables[0];
                    DevControlExtension.ExportToExcel(gridControlForExport, this, textEditShopName.Text);
                    //DevGridViewExport.ExportToExcel(textEditShopName.Text, gridViewForEX);
                    //SaveFileDialog saveFileDialog = new SaveFileDialog();
                    //saveFileDialog.Filter = "文本文件 (*.txt)|*.txt|pdf(*.pdf)|*.pdf|电子表格(*.xls)|*.xls|html(*.html)|*.html";
                    ////saveFileDialog.AddExtension = true;
                    //saveFileDialog.FilterIndex = 3;
                    //saveFileDialog.RestoreDirectory = true;
                    //if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    //{
                    //    string fileName = saveFileDialog.FileName;
                    //    if (saveFileDialog.OpenFile() != null)
                    //    {
                    //        switch (saveFileDialog.FilterIndex)
                    //        {
                    //            case 3:
                    //                XlsExportOptions xo = new XlsExportOptions(true, false, false, false, false);
                    //                gridControlForExport.ExportToXls(fileName, xo);
                    //                //gridViewForEX.ExportToXls(fileName, xo);
                    //                //gridViewForEX.ExportToXls(
                    //                return;
                    //            case 4:
                    //                gridViewForEX.ExportToHtml(fileName);
                    //                return;
                    //            case 2:
                    //                gridViewForEX.ExportToPdf(fileName);
                    //                return;
                    //            case 1:
                    //                this.gridViewForEX.ExportToText(fileName);
                    //                return;
                    //            default:
                    //                break;
                    //        }
                    //    }

                    //}
                }
                else
                {
                    gridControl1.DataSource = setEx.Tables[0];
                    //DevGridViewExport.ExportToExcel(textEditShopName.Text, gridView1);
                    DevControlExtension.ExportToExcel(gridControl1,this,textEditShopName.Text);
                    //SaveFileDialog saveFileDialog = new SaveFileDialog();
                    //saveFileDialog.Filter = "文本文件 (*.txt)|*.txt|pdf(*.pdf)|*.pdf|电子表格(*.xls)|*.xls|html(*.html)|*.html";
                    ////saveFileDialog.AddExtension = true;
                    //saveFileDialog.FilterIndex = 3;
                    //saveFileDialog.RestoreDirectory = true;
                    //if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    //{
                    //    string fileName = saveFileDialog.FileName;
                    //    if (saveFileDialog.OpenFile() != null)
                    //    {
                    //        switch (saveFileDialog.FilterIndex)
                    //        {
                    //            case 3:
                    //                XlsExportOptions xo = new XlsExportOptions(true, false, false, false, false);
                    //                gridControl1.ExportToXls(fileName, xo);
                    //                //gridViewForEX.ExportToXls(fileName, xo);
                    //                //gridViewForEX.ExportToXls(
                    //                return;
                    //            case 4:
                    //                gridView1.ExportToHtml(fileName);
                    //                return;
                    //            case 2:
                    //                gridView1.ExportToPdf(fileName);
                    //                return;
                    //            case 1:
                    //                this.gridView1.ExportToText(fileName);
                    //                return;
                    //            default:
                    //                break;
                    //        }
                    //    }

                    //}

                }
            }
        }

        private void splitContainerBottom2_SplitterMoved(object sender, SplitterEventArgs e)
        {

        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void textEdit1_KeyDown(object sender, KeyEventArgs e)
        {
            if (Keys.Enter == e.KeyCode)
            {
                cbShop.DisplayMember = "ShopName";
                cbShop.ValueMember = "ShopId";
                cbShop.DataSource = _bll.GetShopInfoByFirstChar(textEditStartChar.Text.Trim());


            }
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void textEditShopBillId_EditValueChanged(object sender, EventArgs e)
        {
            textEditProductBarcode.Text = "";
        }

        private void textEditProductBarcode_EditValueChanged(object sender, EventArgs e)
        {
            textEditShopBillId.Text = "";
        }
    }

}
